package com.goldgov.mobile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.gtiles.core.module.auditlog.bean.AuditLogBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.goldgov.auditlog.service.AuditLog;
import com.goldgov.auditlog.service.IAuditLogService;
import com.goldgov.authorityInfo.service.AuthorityInfoInit;
import com.goldgov.branchCircle.service.BranchCircle;
import com.goldgov.branchCircle.service.BranchCircleQuery;
import com.goldgov.branchCircle.service.BranchCircleService;
import com.goldgov.commylog.service.Commylog;
import com.goldgov.commylog.service.CommylogQuery;
import com.goldgov.commylog.service.CommylogService;
import com.goldgov.conference.service.ConferenceService;
import com.goldgov.kcloud.core.json.JsonObject;
import com.goldgov.kcloud.core.json.JsonQueryObject;
import com.goldgov.kcloud.core.json.JsonSuccessObject;
import com.goldgov.login.web.model.LoginAuthUser;
import com.goldgov.ms.adapter.call.RemoteCallService;
import com.goldgov.securityworkbench.attachment.AttachementBean;
import com.goldgov.sensitive.service.Sensitive;
import com.goldgov.sensitive.service.SensitiveService;
import com.goldgov.utils.DataUtil;
import com.goldgov.utils.IpUtil;
import com.goldgov.utils.PrintUtil;
import com.goldgov.utils.PropertyUtil;
import com.goldgov.utils.UrlUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import springfox.documentation.annotations.ApiIgnore;
/**
 * 
 * @<>
 * @author MaN
 * @version 1.0.0
 *
 */
@RestController
@RequestMapping("/mobile/commylog")
@Api("手机工作日志服务接口")
public class CommylogForMobileController{

	@Autowired
	private CommylogService service;
	
	@Autowired
	private RemoteCallService remoteCallService;
	
	@Autowired
	private IAuditLogService auditLogService;
	
	@Autowired
	private SensitiveService sensitiveService;
	
	@Autowired
	private ConferenceService conferenceService;
	@Autowired
	private BranchCircleService branchCircleService;
	
	@GetMapping("/preAddCommylog")
	@ApiOperation(value = "预新增工作日志", notes ="查询日志ID")
	public JsonSuccessObject<Commylog> preAddCommylog(Commylog obj,HttpServletRequest request){
		obj = service.getCommylogID();
		JsonSuccessObject<Commylog> returnResult = new JsonSuccessObject<>(obj);
		return returnResult;
	}
	
	@ResponseBody
	@PostMapping
	@ApiOperation(value = "新增工作日志", notes ="")
	public void addCommylog(Commylog obj, HttpServletRequest request,HttpServletResponse response,Model model) throws IOException {
		try {
			LoginAuthUser u=LoginAuthUser.getUser(request);
			obj.setUserID(u.getEntityID());
			obj.setUserName(u.getName());
			obj.setActiveState(CommylogQuery.ACTIVE_STATE_YES);
			obj.setAuditState(CommylogQuery.AUDIT_STATE_ONE);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(obj.getCreateDate()==null||obj.getCreateDate().equals("")) {
				obj.setCreateDate(sdf.format(new Date()));
			}else {
				SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
				Date date = sdfDate.parse(obj.getCreateDate());
				obj.setCreateDate(sdf.format(date));
			}
			service.addCommylog(obj);
			PrintUtil.printMsg(response, true,"新增成功!");
		} catch (Exception e) {
			PrintUtil.printMsg(response, false,"新增失败!");
			e.printStackTrace();
		}
	}
	@GetMapping("/")
	@ApiOperation(value = "查询多条日志", notes ="日志列表")
	@ApiImplicitParams({ @ApiImplicitParam(name = "searchUserID", value = "日志用户id查询条件", paramType = "query")})
	public JsonQueryObject<Commylog> listCommylog(@ApiIgnore CommylogQuery query,HttpServletRequest request,Model model){
		String userID=query.getSearchUserID();
		if(null==userID || "".equals(userID)) {
			LoginAuthUser u=LoginAuthUser.getUser(request);
			query.setSearchUserID(u.getEntityID());
		}
		//查询部门信息
		if(null!=request.getParameter("type") && !"".equals(request.getParameter("type"))){
			Integer type=Integer.valueOf(request.getParameter("type"));
			Date d=new Date(); 
		    SimpleDateFormat df=new SimpleDateFormat("yyyy-MM-dd");  
		    Calendar c = Calendar.getInstance();
		    c.setTime(d);
		    String endTime="";
		    String beginTime="";
			if(type==0) {//查询最近一周的
				c.add(Calendar.DATE, -7);
				endTime=df.format(d);
				beginTime=df.format(c.getTime());
				query.setSearchCreateDateBegin(beginTime);
				query.setSearchCreateDateEnd(endTime);
			}else if(type==1) {//查询本月的
				c = Calendar.getInstance();  
		        c.add(Calendar.MONTH, 0);  
		        c.set(Calendar.DAY_OF_MONTH, 1);  
		        beginTime = df.format(c.getTime()); 
				endTime=df.format(d);
				beginTime=df.format(c.getTime());
				query.setSearchCreateDateBegin(beginTime);
				query.setSearchCreateDateEnd(endTime);
			}
		}
		List<Commylog> list = service.listCommylog(query);
		if(null!=list && list.size()>0) {
			for(Commylog c:list) {
			    Map params=new HashMap();
				params.put("groupId", c.getCommylogID());
				String resultList=remoteCallService.getForObject("fileListHandler", String.class, params);
				JSONObject json=JSONObject.parseObject(resultList).getJSONObject("data");
				JSONArray jsonList=json.getJSONArray("resultList");
				List<AttachementBean> ab=jsonList.toJavaList(AttachementBean.class);
				for(AttachementBean att:ab) {
					att.setImgUrl(UrlUtil.ATTACHEMEMENT_URL+att.getAttachid());
					if (PropertyUtil.objectNotEmpty(att.getAttachextname()) && DataUtil.isVideo(att.getAttachextname())) {
						att.setDefaultVideoUrl(DataUtil.videoImgUrl(att.getAttachid()));
					}else {
						att.setDefaultVideoUrl(UrlUtil.ATTACHEMEMENT_URL+AttachementBean.DEFAULT_VIDEO_ID);
					}
				}
				c.setFileList(ab);
			}
		}
		Commylog info=service.getUserInfo(query.getSearchUserID());
		if (info != null) {
			if (!list.isEmpty()) {
				list.get(0).setCommylog(info);
			}else {
				Commylog infoq = new Commylog();
				infoq.setCommylog(info);
				list.add(infoq);
			}
		}
//		CommylogExtBean bean=new CommylogExtBean();
//		if (info != null) {
//			if (info.getDuty() != null) {
//				bean.setDuty(info.getDuty());
//			}
//			if (info.getUserName() != null) {
//				bean.setUserName(info.getUserName());
//			}
//			if (info.getUserName() != null) {
//				bean.setOrgName(info.getUserName());
//			}
//		}else {
//			if (!list.isEmpty()) {
//				bean.setUserName(list.get(0).getUserName());
//			}
//		}
		query.setResultList(list);
//		bean.setCommylogList(list);
		return new JsonQueryObject<>(query);
	}
	@PostMapping("/updateCommylogByID")
	@ApiOperation(value = "日志审核", notes ="管理员对日志进行审核")
	public void updateCommylogByID(Commylog obj,HttpServletResponse response,HttpServletRequest request,Model model) {
		LoginAuthUser u=LoginAuthUser.getUser(request);
		obj.setAuditUserID(u.getEntityID());
		obj.setAuditUserName(u.getName());
		if (obj.getAuditValue() != null && !"".equals(obj.getAuditValue()) ) {
			obj.setAuditState(CommylogQuery.AUDIT_STATE_THREEE);
		}else {
			obj.setAuditState(CommylogQuery.AUDIT_STATE_TWO);
		}
		try {
			service.updateCommylogByID(obj);
			PrintUtil.print(response, true);
		} catch (Exception e) {
			e.printStackTrace();
			PrintUtil.print(response, false);
		}
		
	}
	@GetMapping("/{id}")
	@ApiOperation(value = "根据主键查询工作日志", notes ="工作日志详情")
	public JsonSuccessObject<Commylog> getCommylog(@ApiParam(value="commylogID",required=false) @PathVariable("id") String id,
			HttpServletRequest request){
		Commylog obj = service.getCommylog(id);
		Map params=new HashMap();
		params.put("groupId", obj.getCommylogID());
		String resultList=remoteCallService.getForObject("fileListHandler", String.class, params);
		JSONObject json=JSONObject.parseObject(resultList).getJSONObject("data");
		JSONArray jsonList=json.getJSONArray("resultList");
		List<AttachementBean> ab=jsonList.toJavaList(AttachementBean.class);
		for(AttachementBean att:ab) {
			att.setImgUrl(UrlUtil.ATTACHEMEMENT_URL+att.getAttachid());
			if (PropertyUtil.objectNotEmpty(att.getAttachextname()) && DataUtil.isVideo(att.getAttachextname())) {
				att.setDefaultVideoUrl(DataUtil.videoImgUrl(att.getAttachid()));
			}else {
				att.setDefaultVideoUrl(UrlUtil.ATTACHEMEMENT_URL+AttachementBean.DEFAULT_VIDEO_ID);
			}
		}
		obj.setFileList(ab);
		JsonSuccessObject<Commylog> returnResult = new JsonSuccessObject<>(obj);
		return returnResult;
	}
	
	@PutMapping("/")
	@ApiOperation(value = "工作日志更新", notes ="日志更新")
	public void updateCommylog(Commylog obj,HttpServletResponse response) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if(obj.getCreateDate()==null||obj.getCreateDate().equals("")) {
				obj.setCreateDate(sdf.format(new Date()));
			}else {
				SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
				Date date = sdfDate.parse(obj.getCreateDate());
				obj.setCreateDate(sdf.format(date));
			}
			int state = service.updateCommylog(obj);
			if (state >= 1) {
				PrintUtil.printMsg(response, true, "日志更新成功!");
			}else {
				PrintUtil.printMsg(response, false, "日志更新失败!");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@PostMapping("/deleteCommylog")
	@ApiOperation(value = "批量工作日志删除", notes ="删除工作日志")
	public void deleteCommylog(@ApiParam(value = "commylogIDs", required = true) @RequestParam("ids") String[] ids,HttpServletResponse response){
		int state = service.deleteCommylog(ids);
		if (state >= 1) {
			PrintUtil.printMsg(response, true, "日志删除成功!");
		}else {
			PrintUtil.printMsg(response, false, "日志删除失败!");
			
		}
	}
	
	@PostMapping("/shareBranchCircle/{id}")
	@ApiOperation(value = "工作日志分享支部圈", notes ="工作日志分享支部圈")
	public void shareBranchCircle(@ApiParam(value="commylogID",required=false) @PathVariable("id") String id,
			HttpServletRequest request,HttpServletResponse response) {
		Commylog obj = service.getCommylog(id);
		LoginAuthUser u=LoginAuthUser.getUser(request);
		if (u.getEntityID().equals(obj.getUserID())) {
			BranchCircle circle = branchCircleService.getBranchCircleById(obj.getCommylogID());
			if (PropertyUtil.objectNotEmpty(circle)) {
				circle.setBranchContent(obj.getCommylogValue());
				circle.setStatus(BranchCircleQuery.ACTIVESTATE_YES);
				if (branchCircleService.updateBranchCircleById(circle)) {
					PrintUtil.printMsg(response, true, "分享成功");
				}else {
					PrintUtil.printMsg(response, false, "分享失败");
				}
			}else {
				BranchCircle branchCircle = new BranchCircle();
				branchCircle.setBranchID(obj.getCommylogID());
				branchCircle.setOrgID(conferenceService.getOrgIdByUserId(obj.getUserID()));
				branchCircle.setBranchContent(obj.getCommylogValue());
				branchCircle.setUserID(obj.getUserID());
				String msg = this.addBranchCircle(branchCircle, response, request);
				if (PropertyUtil.objectNotEmpty(msg)) {
					PrintUtil.printMsg(response, false, msg);
				}else {
					PrintUtil.printMsg(response, true, "分享成功");
				}
			}
		}else {
			PrintUtil.printMsg(response, false, "只能分享自己的工作日志");
		}
		
		
	}
	
	
	public String addBranchCircle(BranchCircle obj,HttpServletResponse response,HttpServletRequest request){
		String flag=sensitiveService.judgeSensitive(obj.getBranchContent());
		LoginAuthUser u=LoginAuthUser.getUser(request);
		//flag不为空时代表含有关键词
		if(PropertyUtil.objectNotEmpty(flag)) { //不为空时说明含有敏感词
			Sensitive s=new Sensitive();
			s.setCreateDate(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
			s.setDataID(obj.getBranchID());
			s.setDataSource("支部圈");
			s.setDataTitle(obj.getBranchContent());
			s.setTriggerValue(flag);
			s.setDataTable("gt_branch_circle");
			s.setTriggerUserID(u.getEntityID());
			s.setTriggerUserName(u.getName());
			if (PropertyUtil.objectNotEmpty(obj.getOrgID())) {
				s.setOrgID(obj.getOrgID());
			}else {
				s.setOrgID(conferenceService.getOrgIdByCode(LoginAuthUser.getScopeCodeByFunctionID(AuthorityInfoInit.zbq,request)));
			}
			sensitiveService.addSensitive(s);
			return "您发布的内容包含敏感词:"+flag+" 无法分享";
		}else {
			obj.setStatus(BranchCircleQuery.ACTIVESTATE_YES);
			obj.setPublishDate(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));
			if (branchCircleService.addBranchCircle(obj)) {
				return  "";
			} else {
				return  "分享失败！";
			}
		}
	}
	
}
